#ifndef __M_FAT_H__
#define __M_FAT_H__
#include "level.hpp"
#include "message.hpp"
#include <vector>
#include <assert.h>
#include <ctime>
#include <sstream>

namespace whlog
{
    // 抽象格式化基类
    class FormatItem
    {
    public:
        using ptr = std::shared_ptr<FormatItem>;
        virtual void format(std::ostream &out, const LogMsg &msg) = 0;
    };
    // 派生格式化子项子类--消息、等级、时间、文件名、行号、线程ID、日志器名、制表符、换行、其他
    class MsgFormatItem : public FormatItem
    {
    public:
        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << msg._payload;
        }
    };

    class LevelFormatItem : public FormatItem
    {
    public:
        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << LogLevel::toString(msg._level);
        }
    };

    class TimeFormatItem : public FormatItem
    {
    public:
        TimeFormatItem(const std::string &fmt = "%H:%M:%S")
            : _time_fmt_(fmt)
        {
        }
        void format(std::ostream &out, const LogMsg &msg) override
        {
            struct tm t;
            localtime_r(&msg._ctime, &t);
            char tmp[32] = {0};
            strftime(tmp, 31, _time_fmt_.c_str(), &t);
            out << tmp;
        }

    private:
        std::string _time_fmt_;
    };

    class FileFormatItem : public FormatItem
    {
    public:
        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << msg._file;
        }
    };

    class LineFormatItem : public FormatItem
    {
    public:
        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << msg._line;
        }
    };

    class IdFormatItem : public FormatItem
    {
    public:
        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << msg._id;
        }
    };

    class LoggerFormatItem : public FormatItem
    {
    public:
        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << msg._logger;
        }
    };

    class TabFormatItem : public FormatItem
    {
    public:
        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << "\t";
        }
    };

    class NLineFormatItem : public FormatItem
    {
    public:
        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << "\n";
        }
    };

    class OtherFormatItem : public FormatItem
    {
    public:
        OtherFormatItem(const std::string &str)
            : _str(str)
        {
        }
        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << _str;
        }

    private:
        std::string _str;
    };

    class Formatter
    {
    public:
        using ptr = std::shared_ptr<Formatter>;
        Formatter(const std::string &pattern = "[%d{%H:%M:%S}][%t][%c][%f:%l][%p]%T%m%n")
            : _pattern(pattern)
        {
            assert(parsePattern());
        }

        // 对msg进行格式化
        void format(std::ostream &out, const LogMsg &msg)
        {
            for (const auto &item : _items)
            {
                item->format(out, msg);
            }
        }
        std::string format(const LogMsg &msg)
        {
            std::stringstream ss;
            format(ss, msg);
            return ss.str();
        }

    private:
        // 对格式化规则字符串进行解析
        bool parsePattern()
        {
            // 1.对格式化规则字符串进行解析
            std::vector<std::pair<std::string,std::string>> fmt_order;//将此数组填充完后以此对格式化子项数组进行初始化
            size_t pos = 0;
            std::string key, value;

            // abc%%[%d{%H:%M:%S}][%t][%c][%f:%l][%p]%T%m%n
            while(pos < _pattern.size())
            {
                // 1.首先判断是不是'%'，不是就填充进value
                if(_pattern[pos] != '%')
                {
                    value.push_back(_pattern[pos++]); continue;
                }
                // 2.遇到%，判断下一个是不是%
                if(pos + 1 < _pattern.size() && _pattern[pos + 1] == '%')
                {
                    value.push_back(_pattern[pos]);
                    pos += 2;
                    continue;
                }
                // 3.下一个是格式化字符,原始字符串处理完毕
                if(!value.empty()) 
                {
                    fmt_order.push_back(std::make_pair("",value));
                    value.clear();
                }
                pos += 1;
                if(pos == _pattern.size()) 
                {
                    std::cout << "格式错误，接下来没有格式化字符\n";
                    return false;
                }
                key = _pattern[pos];
                // 判断是否有子项
                pos += 1;
                if(pos < _pattern.size() && _pattern[pos] == '{')
                {
                    pos += 1;
                    while(pos < _pattern.size() && _pattern[pos] != '}')
                    {
                        value.push_back(_pattern[pos++]);
                    }
                    if(pos == _pattern.size())
                    {
                        std::cout << "}匹配错误\n";
                        return false;
                    }
                    pos += 1;
                }
                fmt_order.push_back(std::make_pair(key,value));
                key.clear();
                value.clear();
            }
            // 2.根据解析得到的数据进行子项数组成员格式化
            for(const auto& it: fmt_order)
            {
                _items.push_back(createItem(it.first,it.second));
            }
            return true;
        }
        FormatItem::ptr createItem(const std::string &key, const std::string &value)
        {
            /*
                %d 表示日期
                %t 表示线程ID
                %c 表示日志器名称
                %f 表示源码代码文件名
                %l 表示源码行号
                %p 表示日志级别
                %T 表示制表符缩进
                %m 表示主体消息
                %n 表示换行
            */
            if (key == "d")
                return std::make_shared<TimeFormatItem>(value);
            if (key == "t")
                return std::make_shared<IdFormatItem>();
            if (key == "c")
                return std::make_shared<LoggerFormatItem>();
            if (key == "f")
                return std::make_shared<FileFormatItem>();
            if (key == "l")
                return std::make_shared<LineFormatItem>();
            if (key == "p")
                return std::make_shared<LevelFormatItem>();
            if (key == "T")
                return std::make_shared<TabFormatItem>();
            if (key == "m")
                return std::make_shared<MsgFormatItem>();
            if (key == "n")
                return std::make_shared<NLineFormatItem>();
            return std::make_shared<OtherFormatItem>(value);
        }

    private:
        std::string _pattern; // 格式化规则字符串
        std::vector<FormatItem::ptr> _items;
    };

}

#endif